#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/22 0022 11:51
# @Author  : Arliki
# @email   : hkdnxycz@outlook.com
# @File    : qiantu
import pymysql
from twisted.enterprise import adbapi
from scrapy.utils.project import get_project_settings


class dbhelper(object):
    def __init__(self):
        config = get_project_settings()
        db = dict(
            host=config['MYSQL_HOST'],
            db=config['MYSQL_DBNAME'],
            user=config['MYSQL_USER'],
            passwd=config['MYSQL_PASSWD'],
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor,
            use_unicode=False,
        )
        self.dbpool = adbapi.ConnectionPool('pymysql', **db)

    def connect(self):
        return self.dbpool

    def insert(self, item):
        sql = "insert into image (img_url,img_alt,img_name,img_size,img_pixel) VALUES (%s,%s,%s,%s,%s)"
        query = self.dbpool.runInteraction(self._insert, sql, item)
        query.addErrback(self._error)

    def _insert(self, cur, sql, item):
        params = (item['img_url'], item['img_alt'], item['img_name'], item['img_size'], item['img_pixel'])
        cur.execute(sql, params)

    def _error(self, failue):
        print(failue)
